package com.mingdao.lhy.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttribute;

import com.mingdao.lhy.biz.WishFillingBiz;
import com.mingdao.lhy.mapper.signup.SignUpStudentMapper2;
import com.mingdao.lhy.pojo.SignUpStudent;
import com.mingdao.lhy.pojo.page.ChangePassword;
import com.mingdao.lhy.pojo.signup.SignUpStudent2;
import com.mingdao.lhy.service.CityService;

@Controller
@RequestMapping("/signup")
public class StudentController {

	private static Logger log = LoggerFactory.getLogger(StudentController.class);

	/**
	 * #报名起止时间
	 */
	@Value("${bmkssj}")
	private String bmkssj;

	@Value("${bmjssj}")
	private String bmjssj;

	// @Autowired
	// private HttpServletRequest request;

	// @Autowired
	// private WishFillingService wishFillingService;

	@Autowired
	private WishFillingBiz wishFillingBiz;
	@Autowired
	private CityService cityService;

	// @Autowired
	// private HttpSession session;

	// @Autowired
	// private SignUpStudentMapper studentMapper;

	@Autowired
	private SignUpStudentMapper2 studentMapper2;

	// @Autowired
	// private XueJiMapper xueJiMapper;

	/**
	 * 学生报名登录页面
	 * 
	 * @return
	 */
	@RequestMapping("")
	public String index(Model model) {

		Date today = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println("当前时间：" + sdf.format(today));

		// if(wishFillingBiz.isEffectiveDate(today, Constant.YTTC_START_TIME,
		// Constant.YTTC_END_TIME)) {
		//
		// }
		SignUpStudent2 student = new SignUpStudent2();
		model.addAttribute("student", student);
		// session.setAttribute("student", student);
		// model.addAttribute("msg","");
		// wishFillingService.getAllHighSchool();
		return "loginSignUpStudent";
	}

	@RequestMapping(value = "/transforms")
	public String indexTransform(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		SignUpStudent2 student = (SignUpStudent2) session.getAttribute("student");
		model.addAttribute("student", student);
		return "transform";
	}

	/**
	 * 学生志愿填报登录验证页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "check", method = RequestMethod.POST)
	public String check(@ModelAttribute("student") SignUpStudent2 student, Model model, HttpServletResponse response) {

		HttpSession session = wishFillingBiz.getSession();

		log.debug("进入【学生志愿填报登录验证页面】");
		if (null == student || null == student.getSfzh() || null == student.getPassword()) {
			log.error("没有收到有效的请求数据");
			model.addAttribute("msg", "没有收到有效的请求数据");
			return "/signup/loginStudent";
		}
		/**
		 * 根据报名号查询学生信息
		 */
		/**
		 * 判断当前登录学生是否有效（是否为州外学生，是的话不允许填报志愿）
		 */

		// 调用业务逻辑查询对应的学生信息
		SignUpStudent2 dbStudent = new SignUpStudent2();
		dbStudent = studentMapper2.getOne(student.getSfzh());
		if (null == dbStudent) {
			log.error("没有找到指定报名号的学生");
			model.addAttribute("result", "没有找到指定的学生，检查报名号");
			response.setCharacterEncoding("UTF-8");
			try {
				response.getWriter().write("<script>alert('没有找到指定的学生，检查报名号');</script>");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "/signup/loginStudent";
		}

		/**
		 * 判断学生是否第一次登录（如果密码为空，或者和身份证后8位相同则是初次登录）
		 * 
		 * 如果是，跳转到修改密码界面，如果不是，则继续前进到志愿填报页面
		 */
		String sfzhLast8 = dbStudent.getSfzh().substring(10, 18);
		String dbPassword = dbStudent.getPassword();
		if (null == dbPassword || (dbPassword.equals(sfzhLast8) && dbPassword.equals(student.getPassword()))) {
			log.debug("学生初次登录 ，进入【密码修改页面】");
			SignUpStudent st = new SignUpStudent();
			st.setSfzh(dbStudent.getSfzh());
			st.setPassword(student.getPassword());
			st.setXm(dbStudent.getXm());
			model.addAttribute("student", dbStudent);
			session.setAttribute("student", st);
			// model.addAttribute("changePassword",new ChangePassword());
			return "changePasswd";

		}
		// dbStudent.setPassword(student.getPassword());
		// dbStudent.setXm("测试用户");
		// dbStudent.setBmh(student.getBmh());

		// 验证是否找到对应的学生
		// 并且输入的密码是否和查找到的学生密码是否一致
		if (null != dbStudent.getPassword() && dbStudent.getPassword().equals(student.getPassword())) {

			// 验证成功转到填报页面
			log.debug("验证【成功】");

			log.info(dbStudent.getBmh());
			log.debug(dbStudent.getSfzh());
			model.addAttribute("student", dbStudent);
			if (null == session) {
				session = wishFillingBiz.getSession();
			}
			session.setAttribute("student", dbStudent);

			// ResponseVo vo = new ResponseVo();
			// model.addAttribute("vo",vo);

			// 转到选择操作页面，根据页面选择再转向具体功能页面
			return "signup/StudentEnrolmentInfo";
		} else {
			// 验证失败继续回到登录页面
			// Model model = new Model();
			log.debug("验证【失败】");

			model.addAttribute("result", "验证失败，报名号或密码不正确");
			return "signup/loginStudent";
		}

	}

	/**
	 * 安全退出，返回登录页面
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/loginOut", method = RequestMethod.POST)
	public String loginOut(@ModelAttribute("session") Session session, HttpServletRequest request) {

		// 清除session
		Enumeration<String> em = request.getSession().getAttributeNames();

		while (em.hasMoreElements()) {
			request.getSession().removeAttribute(em.nextElement().toString());

		}

		request.getSession().removeAttribute("session");
		request.getSession().removeAttribute("student");
		request.getSession().invalidate();

		return "redirect:" + "/login";

	}

	/**
	 * 学生报名
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "doSignUpStudent", method = RequestMethod.GET)
	public String signUpStudent(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("student")) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "redirect:/";
		}
		SignUpStudent2 student = (SignUpStudent2) session.getAttribute("student");
		/**
		 * 查询学生的学籍信息，然后跳转到报名信息详细页面
		 */

		SignUpStudent2 signUpStudent2 = studentMapper2.getOneXueJi(student.getSfzh());
		model.addAttribute("student", signUpStudent2);
		// TODO 确定学生报名详情页面名称
		return "sign/StudentEnrolmentInfo";
	}

	/**
	 * 学生报名登录
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(Model model) {
		return "signup/loginStSignUp";
	}

	/**
	 * 学生报名
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "doSaveSignUpStudent", method = RequestMethod.POST)
	public String saveSignUpStudent(@ModelAttribute("signUpStudent") SignUpStudent2 signUpStudent, Model model,
			HttpServletResponse response) {
		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("student")) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "redirect:/";
		}
		SignUpStudent2 student = (SignUpStudent2) session.getAttribute("student");
		// add by jxb 2018-12-29 content:if if-else
		String hjd = signUpStudent.getHjd();
		if (!hjd.isEmpty()) {
			// 如果最后一个字符为逗号，则没有选择到最后(街道)
			if (",".equals(hjd.substring(hjd.length() - 1, hjd.length())))
				// 获取最后一个值 ex: 11,22,33, --> 33
				signUpStudent.setHjd(
						hjd.substring(hjd.substring(0, hjd.length() - 1).lastIndexOf(",") + 1, hjd.length() - 1));
			else // 如果最后一个字符不为逗号，那么一定是选择到最后(街道)，获取最后一个街道编码即可
					// 11,22,33,44 ---> 44
				signUpStudent.setHjd(hjd.substring(hjd.lastIndexOf(",") + 1, hjd.length()));
		}
		/**
		 * 查询学生的学籍信息，然后跳转到报名信息详细页面
		 */
		SignUpStudent2 signUpStudent2 = studentMapper2.getOne(student.getSfzh());
		// 根据身份证号处理性别
		if (1 == Integer.parseInt(signUpStudent.getSfzh().substring(16, 17)) % 2) {
			// 奇数为男
			signUpStudent.setXb("1");
		} else {
			// 偶数为女
			signUpStudent.setXb("2");
		}
		if (null == signUpStudent2) {
			// 待处理状态，1：确定，2：待定
			signUpStudent.setDclzt("1");
			// 处理就读地：学校代码对应的就读地区行政代码
			// TODO
			signUpStudent.setJdd(student.getByzxdm().substring(0, 4));
			// 将学籍库密码复制到报名库
			signUpStudent.setPassword(student.getPassword());
			// TODO 网报序号如何生成？ 已改成数据自增长类型
			// signUpStudent.setWbxh(UUID.randomUUID().getLeastSignificantBits() + "");

			studentMapper2.insertSelective(signUpStudent);
		} else {
			studentMapper2.updateByStudentSelective(signUpStudent);
		}

		try {
			response.setCharacterEncoding("UTF-8");
			response.getWriter().write("<script>alert('保存成功！');</script>");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SignUpStudent2 dbStudent = new SignUpStudent2();
		dbStudent = studentMapper2.getOne(student.getSfzh());
		session.setAttribute("student", dbStudent);
		model.addAttribute("student", dbStudent);
		// return "";
		// TODO 确定学生报名详情页面名称
		return "signup/StudentEnrolmentInfo";
	}

	/**
	 * 拍照页面
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/getPhoto", method = RequestMethod.GET)
	public String photo(@ModelAttribute("session") Session session, HttpServletRequest request) {

		// 清除session
		Enumeration<String> em = request.getSession().getAttributeNames();

		while (em.hasMoreElements()) {
			request.getSession().removeAttribute(em.nextElement().toString());

		}

		request.getSession().removeAttribute("session");
		request.getSession().removeAttribute("student");
		request.getSession().invalidate();

		// return "redirect:" + "";

		return "signup/webcam";

	}

	/**
	 * 学生报名登录验证页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "checkSignUp", method = RequestMethod.POST)
	public String checkSignUp(@ModelAttribute("student") SignUpStudent2 student, Model model,
			HttpServletResponse response) {

		HttpSession session = wishFillingBiz.getSession();

		log.debug("进入【学生报名登录验证页面】");
		if (null == student || null == student.getSfzh() || null == student.getPassword()) {
			log.error("没有收到有效的请求数据");
			model.addAttribute("msg", "没有收到有效的请求数据");
			return "signup/loginStSignUp";
		}

		/**
		 * 报名时间判断
		 */
		Date day = new Date();

		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			
			response.setCharacterEncoding("UTF-8");
			
			Date now = df.parse(df.format(day)); // 当前时间
			Date startTime = df.parse(bmkssj);
			Date endTime = df.parse(bmjssj); // 截止时间
			if (now.before(endTime) && now.after(startTime)) {
				// 继续正常处理
				System.out.println("继续正常处理");

			} else {
				model.addAttribute("message", "非报名时间，不能报名");
				response.getWriter().write("<script>alert('非报名时间，不能报名');</script>");
				return "signup/loginStSignUp";
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			return "signup/loginStSignUp";
		}

		student.setPassword(student.getPassword());
		// 调用业务逻辑查询对应的学生信息
		SignUpStudent2 dbStudent = new SignUpStudent2();
		dbStudent = studentMapper2.getOne(student.getSfzh());
		/**
		 * 先从已报名信息表中查找学生
		 */
		if (null == dbStudent) {
			dbStudent = new SignUpStudent2();
			dbStudent = studentMapper2.getOneXueJi(student.getSfzh());
			// 如果没找到即为未报名学生，进入学籍表查询
			if (null == dbStudent) {
				log.error("没有找到指定的学生");
				model.addAttribute("result", "没有找到指定的学生，检查身份证号");
				response.setCharacterEncoding("UTF-8");
				try {
					response.getWriter().write("<script>alert('没有找到指定的学生，检查身份证号')</script>");
					response.getWriter().write("<link href='css/index.css' rel='stylesheet' type='text/css' />");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return "signup/loginStSignUp";
			}
		}

		/**
		 * 判断学生是否第一次登录（如果密码为空，或者和身份证后8位相同则是初次登录）
		 * 
		 * 如果是，跳转到修改密码界面，如果不是，则继续前进到志愿填报页面
		 */
		/**
		 * String sfzhLast8 = dbStudent.getSfzh().substring(12, 18); String dbPassword =
		 * dbStudent.getPassword(); if (null == dbPassword ||
		 * (dbPassword.equals(sfzhLast8) && dbPassword.equals(student.getPassword()))) {
		 * log.debug("学生初次登录 ，进入【密码修改页面】"); model.addAttribute("student", dbStudent);
		 * session.setAttribute("student", dbStudent); //
		 * model.addAttribute("changePassword",new ChangePassword()); return
		 * "changePasswd";
		 * 
		 * }
		 */

		// 验证是否找到对应的学生
		// 并且输入的密码是否和查找到的学生密码是否一致
		if (null != dbStudent.getPassword() && dbStudent.getPassword().equals(student.getPassword())) {

			// 验证成功转到填报页面
			log.debug("验证【成功】");

			log.info(dbStudent.getBmh());
			log.debug(dbStudent.getSfzh());
			model.addAttribute("student", dbStudent);
			if (null == session) {
				session = wishFillingBiz.getSession();
			}
			session.setAttribute("student", dbStudent);

			// ResponseVo vo = new ResponseVo();
			// model.addAttribute("vo",vo);
			// 根据身份证号处理性别
			if (1 == Integer.parseInt(dbStudent.getSfzh().substring(16, 17)) % 2) {
				// 奇数为男
				dbStudent.setXb("1");
			} else {
				// 偶数为女
				dbStudent.setXb("2");
			}

			// 转到选择操作页面，根据页面选择再转向具体功能页面
			return "signup/StudentEnrolmentInfo";
		} else {
			// 验证失败继续回到登录页面
			// Model model = new Model();
			log.debug("验证【失败】");

			model.addAttribute("result", "验证失败，身份証或密码不正确");
			response.setCharacterEncoding("UTF-8");
			try {
				response.getWriter().write("<script>alert('身份证或密码错误')</script>");
				response.getWriter().write("<link href='css/index.css' rel='stylesheet' type='text/css' />");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "signup/loginStSignUp";

		}

	}

	/**
	 * 修改密码
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("changePasswd")
	public String changePasswd(Model model) {
		HttpSession session = wishFillingBiz.getSession();
		SignUpStudent2 student = (SignUpStudent2) session.getAttribute("student");
		model.addAttribute("student", student);
		return "/signup/changePasswd";
	}

	/**
	 * 安全退出，返回报名页面
	 * 
	 * @param request
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/loginOutToBM", method = RequestMethod.POST)
	public String loginOutToBM(@ModelAttribute("session") Session session, HttpServletRequest request) {

		// 清除session
		Enumeration<String> em = request.getSession().getAttributeNames();

		while (em.hasMoreElements()) {
			request.getSession().removeAttribute(em.nextElement().toString());

		}

		request.getSession().removeAttribute("session");
		request.getSession().removeAttribute("student");
		request.getSession().invalidate();

		return "signup/loginStSignUp";

	}

	@RequestMapping(value = "doSaveStudnet", method = RequestMethod.POST)
	public String doSaveStudnet(SignUpStudent2 student, HttpServletResponse response) {
		HttpSession session = wishFillingBiz.getSession();

		try {
			int count = cityService.doSaveStudnet(student);

			// response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			if (count > 0)
				response.getWriter().write("<script>alert('添加成功');</script>");
			else
				response.getWriter().write("<script>alert('添加失败');</script>");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "signup/StudentEnrolmentInfo";
	}

	@RequestMapping(value = "doChangePasswd", method = RequestMethod.POST)
	public String changePwd(@ModelAttribute(value = "changePassword") ChangePassword changePassword,
			@SessionAttribute SignUpStudent2 student, Model model) {

		HttpSession session = wishFillingBiz.getSession();
		if (null == session || null == session.getAttribute("student")) {
			session = null;
			log.error("用户未登录，请重新登录");
			return "redirect:/signup/loginStSignUp";
		}
		student = (SignUpStudent2) session.getAttribute("student");
		/**
		 * 判断传入的密码
		 */
		if (null == model || null == model.asMap() || null == model.asMap().get("changePassword")) {
			log.error("未取到前台返回的密码值 ");
			model.addAttribute("msg", "未取到前台返回的密码值");
			// model.addAttribute("student", student);
			return "/signup/changePasswd";
		}
		// SignUpStudent student1 = (SignUpStudent) model.asMap().get("student");
		ChangePassword cp = (ChangePassword) model.asMap().get("changePassword");
		if (null == cp.getOldPassword()) {
			log.error("必须输入原来的密码值 ");
			model.addAttribute("msg", "必须输入原来的密码值");
			// model.addAttribute("student", student);
			return "check";
		}
		if (null == cp.getNewPasswordOne() || null == cp.getNewPasswordTwo()) {
			log.error("必须输入新的码值 ");
			model.addAttribute("msg", "必须输入新的码值");
			// model.addAttribute("student", student);
			return "/signup/changePasswd";
		}

		String oldPassword = cp.getOldPassword();
		String newPasswordOne = cp.getNewPasswordOne();
		String newPasswordTwo = cp.getNewPasswordTwo();

		/**
		 * 如果输入的旧密码等于学生本来的旧密码才可以更换密码
		 */
		if (!oldPassword.isEmpty() && !student.getPassword().isEmpty()) {
			if (oldPassword.equals(student.getPassword())) {
				/**
				 * 两次输入密码要一致才有效
				 */
				if (newPasswordOne.equals(newPasswordTwo)) {
					student.setPassword(newPasswordOne);
				} else {
					log.error("两次密码不符，请重新核对 ");
					model.addAttribute("msg", "两次密码不符，请重新核对 ");
					model.addAttribute("student", student);
					return "/signup/changePasswd";
				}
			} else {
				log.error("原密码不符，请重新核对 ");
				model.addAttribute("msg", "原密码不符，请重新核对 ");
				model.addAttribute("student", student);
				return "/signup/changePasswd";
			}
		}
		/**
		 * 修改密码
		 */
		int result = studentMapper2.updatePasswordByPrimaryKey(student);
		if (1 == result) {
			log.debug("密码修改成功");
		} else {
			log.warn("密码修改失败");
			model.addAttribute("student", student);
			return "/signup/changePasswd";
		}
		/**
		 * 跳转到登录界面重新登录
		 */
		return "/signup/loginStSignUp";
	}
}
